﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using log4net;
using Quartz;
using Quartz.Impl;
using Topshelf;

namespace Mgx.Job
{
    public class JobService
    {
        private ISchedulerFactory _schedulerFactory;
        private ILog _logger = log4net.LogManager.GetLogger(typeof(JobService));

        public JobService()
        {
            this._schedulerFactory = new StdSchedulerFactory();
        }

        static void Main(string[] args)
        {
            var host = HostFactory.New(config =>
            {
                config.Service<JobService>(
                    settings =>
                    {
                        settings.ConstructUsing(job => new JobService());
                        settings.WhenStarted(job => job.Start());
                        settings.WhenStopped(job => job.Stop());
                    });
                config.RunAsLocalSystem();
                config.SetDescription("Mgx.Job信息处理");
                config.SetDisplayName("Mgx.Job信息处理");
                config.SetServiceName("Mgx.Job");
            });
            host.Run();
        }

        private void Start()
        {
            _logger.Info("任务开始启动");

            try
            {
                IScheduler scheduler = this._schedulerFactory.GetScheduler();
                scheduler.Start();
            }
            catch (Exception ex)
            {
                _logger.Error("任务启动异常：" + ex);
            }

            _logger.Info("任务启动成功");
        }

        private void Stop()
        {
            _logger.Info("任务开始关闭");

            try
            {
                IScheduler scheduler = this._schedulerFactory.GetScheduler();
                scheduler.Shutdown();
            }
            catch (Exception ex)
            {
                _logger.Error("任务启关闭异常：" + ex);
            }

            _logger.Info("任务关闭成功");
        }

    }
}
